package com.zxn.ssyx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxn.ssyx.mapper.PermissionMapper;
import com.zxn.ssyx.model.acl.Permission;
import com.zxn.ssyx.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Permission> getWithTree() {
        // 1.获取所有permission
        List<Permission> permissionList = permissionMapper.selectList(null);

        // 2.根据id存成map
        Map<Long, Permission> idToPermissionMap = permissionList.stream()
                .collect(Collectors.toMap(Permission::getId, permission -> permission));

        // 3.遍历处理
        return permissionList.stream()
                .filter(permission -> permission.getPid() == 0)
                .map(root -> {
                    root.setLevel(1);
                    root.setChildren(getChildrens(root, idToPermissionMap));
                    return root;
                })
                .collect(Collectors.toList());
    }

    @Override
    public boolean removeChildById(Long id) {
        List<Long> idList = new ArrayList<>();
        idList.add(id);
        selectChildListById(id,idList);
        int result = permissionMapper.deleteBatchIds(idList);
        return result > 0;
    }

    // 存储所有子节点
    public void selectChildListById(Long id,List<Long> idList){
        List<Permission> childList = permissionMapper.selectList(new QueryWrapper<Permission>().eq("pid", id).select("id"));
        childList.forEach(child->{
            idList.add(child.getId());
            selectChildListById(child.getId(),idList);
        });
    }

    // 遍历获取子树
    private List<Permission> getChildrens(Permission root, Map<Long, Permission> idToPermissionMap) {
        return idToPermissionMap.entrySet().stream()
                .filter(entry -> Objects.equals(entry.getValue().getPid(), root.getId()))
                .map(entry -> {
                    Permission child = entry.getValue();
                    child.setLevel(root.getLevel() + 1);
                    child.setChildren(getChildrens(child, idToPermissionMap));
                    return child;
                })
                .collect(Collectors.toList());
    }
}
